package main

import (
	"context"
	"log"

	"learn-go-demo/pkg/discovery"
	pb "learn-go-demo/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	registry := discovery.NewServiceRegistry()

	// 测试用户服务
	log.Println("=== 测试用户服务 ===")
	testUserService(registry)

	// 测试订单服务
	log.Println("\n=== 测试订单服务 ===")
	testOrderService(registry)
}

func testUserService(registry *discovery.ServiceRegistry) {
	userAddrs, err := registry.Discover("user-service")
	if err != nil || len(userAddrs) == 0 {
		log.Printf("Failed to discover user service: %v", err)
		return
	}

	conn, err := grpc.Dial(userAddrs[0], grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Printf("Failed to connect to user service: %v", err)
		return
	}
	defer conn.Close()

	client := pb.NewUserServiceClient(conn)

	// 创建用户
	createResp, err := client.CreateUser(context.Background(), &pb.CreateUserRequest{
		Name:  "Test User",
		Email: "test@example.com",
	})
	if err != nil {
		log.Printf("CreateUser failed: %v", err)
		return
	}
	log.Printf("User created: ID=%d, Message=%s", createResp.Id, createResp.Message)

	// 获取用户
	getResp, err := client.GetUser(context.Background(), &pb.GetUserRequest{
		Id: createResp.Id,
	})
	if err != nil {
		log.Printf("GetUser failed: %v", err)
		return
	}
	log.Printf("User retrieved: ID=%d, Name=%s, Email=%s", getResp.Id, getResp.Name, getResp.Email)
}

func testOrderService(registry *discovery.ServiceRegistry) {
	orderAddrs, err := registry.Discover("order-service")
	if err != nil || len(orderAddrs) == 0 {
		log.Printf("Failed to discover order service: %v", err)
		return
	}

	conn, err := grpc.Dial(orderAddrs[0], grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Printf("Failed to connect to order service: %v", err)
		return
	}
	defer conn.Close()

	client := pb.NewOrderServiceClient(conn)

	// 创建订单
	createResp, err := client.CreateOrder(context.Background(), &pb.CreateOrderRequest{
		UserId:  1,
		Product: "Test Product",
		Amount:  99.99,
	})
	if err != nil {
		log.Printf("CreateOrder failed: %v", err)
		return
	}
	log.Printf("Order created: ID=%d, Message=%s", createResp.OrderId, createResp.Message)

	// 获取订单
	getResp, err := client.GetOrder(context.Background(), &pb.GetOrderRequest{
		OrderId: createResp.OrderId,
	})
	if err != nil {
		log.Printf("GetOrder failed: %v", err)
		return
	}
	log.Printf("Order retrieved: ID=%d, UserID=%d, Product=%s, Amount=%.2f",
		getResp.OrderId, getResp.UserId, getResp.Product, getResp.Amount)
}
